package com.mimi.controller;

import com.lly835.bestpay.model.PayResponse;
import com.mimi.dto.OrderDTO;
import com.mimi.enums.ResultEnum;
import com.mimi.exception.SellException;
import com.mimi.service.OrderService;
import com.mimi.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @Author:徐向
 * @Description:支付
 * @Date: Created in 15:58 2017/10/13
 */
@Controller
//@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    @GetMapping("/pay")
    public ModelAndView index(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl, Map<String, Object> map) {
        //1.查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //发起支付
        PayResponse payResponse = payService.create(orderDTO);
        String url = "";
        try {
            url = URLDecoder.decode(returnUrl, "utf-8");
            map.put("payResponse", payResponse);
            map.put("returnUrl", url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        log.info("=====returnUrl:{}", returnUrl);
        log.info("=====rul:{}", url);

        return new ModelAndView("pay/create", map);
    }

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl, Map<String, Object> map) {
        //1.查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);

        return new ModelAndView("pay/create", map);
    }

    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);
        //返回微信处理结果
        return new ModelAndView("pay/success");
    }
}
